using System;
using System.Collections;
using System.Collections.Generic;
using Unity.Burst;
using Unity.Collections;
using Unity.Jobs;
using Unity.Mathematics;
using UnityEngine;

public class Main : MonoBehaviour
{
    public Mesh m_mesh;
    public Material m_material;
    private BRG_Container m_brgContainer;
    
    private int m_itemCount = 4;
    private NativeArray<float4> sysmemBuffer;
    
    public struct BackgroundItem
    {
        public float x;
        public float hInitial;
        public float h;     // scale
        public float phase;
        public int weight;
        public float magnetIntensity;
        public float flashTime;
        public Vector4 color;
    };

    void Start()
    {
        m_brgContainer = new BRG_Container();
        m_brgContainer.Init(m_mesh, m_material, m_itemCount, false);
        
        m_brgContainer.UploadGpuData(m_itemCount);
    }
    
    void Update()
    {
        int totalGpuBufferSize;
        int alignedWindowSize;
        sysmemBuffer = m_brgContainer.GetSysmemBuffer(out totalGpuBufferSize, out alignedWindowSize);

        var _maxInstancePerWindow = alignedWindowSize / BRG_Container.InstanceSize;
        
        int offset = 0;
        int posOffset = 4;
        for(int i=0; i< m_itemCount; i++)
        {
            offset = i*3;
            //计算矩阵
            //矩阵数据以列主序(column-major)方式存储，而不是行主序。Unity的GPU矩阵存储使用列主序，这意味着矩阵的列连续存储
            // [1,  0,      0,  bpos.x]
            // [0,  scaleY, 0,  bpos.y]
            // [0,  0,      1,  pz]
            sysmemBuffer[(offset + 0)] = new float4(1, 0, 0, 0);
            sysmemBuffer[(offset + 1)] = new float4(i+1, 0, 0, 0);
            sysmemBuffer[(offset + 2)] = new float4(1, 2*i, 0, 0);


            offset = 3 * (_maxInstancePerWindow + i);
            // compute the new inverse matrix (note: shortcut use identity because aligned cubes normals aren't affected by any non uniform scale
            sysmemBuffer[(offset + 0)] = new float4(1, 0, 0, 0);
            sysmemBuffer[(offset + 1)] = new float4(1, 0, 0, 0);
            sysmemBuffer[(offset + 2)] = new float4(1, 0, 0, 0);
        
            offset = 6 * _maxInstancePerWindow + i;
            // update colors
            sysmemBuffer[offset] = new float4(1.0f, 0.5f, 1f, 0);
        }
    }

    private void LateUpdate()
    {
        m_brgContainer.UploadGpuData(m_itemCount);
    }
}
